import 'dart:convert';

import 'package:event_bus/event_bus.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:leader_doctor_flutter/common/data/app.dart';
import 'package:leader_doctor_flutter/common/http/api.dart';
import 'package:leader_doctor_flutter/common/http/http_client.dart';
import 'package:leader_doctor_flutter/common/utils/app_fonts.dart';
import 'package:leader_doctor_flutter/common/utils/image_utils.dart';
import 'package:leader_doctor_flutter/common/widget/comm_widget.dart';
import 'package:leader_doctor_flutter/common/widget/refresh_custom_widget.dart';
import 'package:leader_doctor_flutter/common/widget/table_placeholder_widget.dart';
import 'package:leader_doctor_flutter/model/my_doctor_service_list_model.dart';
import 'package:leader_doctor_flutter/model/my_project_outcome_top_tabbar.dart';
import 'package:leader_doctor_flutter/router/router.dart';
import 'package:leader_doctor_flutter/styles/colors.dart';
import 'package:leader_doctor_flutter/ui/mine/page/event/refresh_event.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class MyDoctorServicePage extends StatefulWidget {
  const MyDoctorServicePage({super.key});

  @override
  State<MyDoctorServicePage> createState() => _MyDoctorServicePageState();
}

class _MyDoctorServicePageState extends State<MyDoctorServicePage> {
  var pageSize = 20;
  var pageNo = 1;
  bool dataLoaded = false; // 数据请求中

  String tabbarKey = "";

  List<MyProjectOutcomeTopTabbarModel> topTabbarArray = [];
  List<MyDoctorServiceListModel> dataArray = [];

  final RefreshController _refreshController = RefreshController(initialRefresh: false);

  int refundCount = 0;

  void _onRefresh() async {
    pageNo = 1;
    _getDoctorServiceList();
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    pageNo++;
    _getDoctorServiceList();
    _refreshController.loadComplete();
  }

  @override
  void initState() {
    super.initState();

    App.instance.eventBus.on<RefreshEvent>().listen((event) {
      pageNo = 1;
      _getRefundApplicationList();
      // _getDoctorServiceList();
      print("服务列表接收到了发的通知");
    });

    List tabBarList = [
      {"name": "全部", "value": ""},
      {"name": "未使用", "value": "untreated"},
      {"name": "已使用", "value": "finish"},
      {"name": "已退款", "value": "refund"},
    ];
    List<MyProjectOutcomeTopTabbarModel> tmpList =
        tabBarList.map((e) => MyProjectOutcomeTopTabbarModel.fromJson(e)).toList();
    topTabbarArray.addAll(tmpList);
    _getRefundApplicationList();
    // _getDoctorServiceList();
  }

  @override
  Widget build(BuildContext context) {
    return contentView();
  }

  Widget contentView() {
    return DefaultTabController(
        length: topTabbarArray.length,
        child: Scaffold(
          appBar: CommWidget.getCommAppbar(context, title: "医生服务", actions: appBarRightActions()),
          body: Container(
            // width: double.infinity,
            color: ColorRes.white,
            child: Column(
              children: [
                Container(
                  child: myTabBar(),
                ),
                Expanded(
                  child: PageView(
                    physics: NeverScrollableScrollPhysics(),
                    children: topTabbarArray.map((tab) {
                      return SmartRefresher(
                        controller: _refreshController,
                        enablePullDown: true,
                        enablePullUp: true,
                        onRefresh: _onRefresh,
                        onLoading: _onLoading,
                        header: RefreshCustomHeaderWidget(),
                        footer: RefreshCustomFooterWidget(),
                        child: dataLoaded
                            ? dataArray.isEmpty
                                ? TablePlaceholderWidget(
                                    message: "暂无数据",
                                    yOffset: -30,
                                  )
                                : ListView.builder(
                                    itemCount: dataArray.length,
                                    itemBuilder: (BuildContext context, int index) {
                                      return _buildListItem(dataArray[index], tabbarKey);
                                    },
                                  )
                            : Container(),
                      );
                    }).toList(),
                  ),
                ),
              ],
            ),
          ),
        ));
  }

  List<Widget> appBarRightActions() {
// 创建一个红点的Widget
    Widget redDot = Container(
      width: 8.0,
      height: 8.0,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        color: Colors.red,
      ),
    );

    return [
      Container(
        padding: EdgeInsets.only(right: 5.w),
        child: Stack(
          alignment: Alignment.centerRight,
          children: [
            TextButton(
              onPressed: () {
                // 处理按钮点击事件
                print("退款申请");
                context.push(PageUrl.doctorServiceRefundApplicationList);
              },
              child: Text(
                '退款申请',
                style: TextStyle(
                  color: ColorRes.colorMain,
                  fontSize: 15.sp,
                ),
              ),
            ),
            if (refundCount > 0)
              // 这是红点，它会被放置在按钮的右上角
              Positioned(
                right: 0.w,
                top: 15.w,
                child: redDot,
              ),
          ],
        ),
      )
    ];
  }

  Widget myTabBar() {
    return TabBar(
      tabs: topTabbarArray.map((e) => Tab(text: e.name)).toList(),
      onTap: (index) {
        MyProjectOutcomeTopTabbarModel model = topTabbarArray[index];
        tabbarKey = model.value ?? "";
        print("object = ${model.value}");
        pageNo = 1;
        _getDoctorServiceList();
      },
      isScrollable: false,
      //是否可以滑动，标题左右滑动
      padding: EdgeInsets.only(top: 1.w, left: 10.w, right: 10.w, bottom: 5.w),
      indicatorWeight: 1.w,
      //指示器高度
      indicator: UnderlineTabIndicator(
        borderSide: BorderSide(width: 2.w, color: ColorRes.colorMain), //高度和颜色
        borderRadius: BorderRadius.all(Radius.circular(1.w)),
        insets: EdgeInsets.only(left: 30.w, right: 30.w), //左右间距反向设置长度
      ),
      labelColor: ColorRes.colorMain,
      //标题选择时颜色
      unselectedLabelColor: ColorRes.color333333,
      //未被选择时颜色
      labelStyle: TextStyle(
        fontSize: 14.sp,
        fontFamily: AppFonts.pingFangSC,
        fontWeight: AppFonts.medium,
      ), //被选择时label风格样式
    );
  }

  Widget _buildListItem(MyDoctorServiceListModel model, String tabbarKey) {
    var user = App.instance.userInfo;
    String patientNameStr = model.patientName ?? "";
    String sexStr = model.sex ?? "";
    String ageStr = model.age ?? "";
    sexStr = sexStr == "1" ? "男" : "女";
    String ageAndSex = sexStr + " | " + ageStr + "岁";
    // 订单来源医生
    String orderSourceDoctor = model.orderSource ?? "";
    // 医生姓名
    String doctorName = model.doctorName ?? "";
    // 所有医生Id
    String belongDoctorId = model.doctorId ?? "";
    // 所有医生
    String belongDoctor = "";
    if (belongDoctorId != user?.id) {
      belongDoctor = doctorName;
    }

    // 购买时间
    String payTime = model.payTime ?? "";
    int servicePrice = model.price ?? 0;
    String servicePriceStr = (servicePrice / 100).toStringAsFixed(2);

    // 第三行标题
    String thirdLineTitleStr = "";
    // 第三行描述
    String thirdLineDescStr = "";
    // 第三行标题颜色
    Color thirdLineTitleColor = ColorRes.color666666;
    // 第三行描述颜色
    Color thirdLineDescColor = ColorRes.color333333;

    // 第四行标题
    String fourLineTitleStr = "";
    // 第四行描述
    String fourLineDescStr = "";
    // 第四行标题颜色
    Color fourLineTitleColor = ColorRes.color666666;
    // 第四行描述颜色
    Color fourLineDescColor = ColorRes.color333333;

    // 第五行标题
    String fiveLineTitleStr = "";
    // 第五行标题颜色
    Color fiveLineTitleColor = ColorRes.color666666;

    // 订单使用状态
    String status = model.status ?? "";

    Color statusColor = ColorRes.color666666;
    String statusStr = "";
    if (status == "untreated") {
      // 未使用
      statusStr = "未使用";
      statusColor = ColorRes.color666666;
    } else if (status == "finish") {
      // 已使用
      statusStr = "已使用";
      statusColor = Color(0xFF2AA515);
    } else if (status == "refund") {
      // 已退款
      statusStr = "已退款";
      statusColor = ColorRes.color666666;
    }

    // 订单支付状态
    String payStatus = model.payStatus ?? "";
    String payStatusStr = "";
    if (payStatus == "toPay") {
      // 未支付
      payStatusStr = "未支付";
      thirdLineTitleStr = payStatusStr;
      thirdLineTitleColor = const Color(0xFFFF1800);
    } else {
      if (payStatus == "refunding") {
        // 申请退款
        payStatusStr = "申请退款";
        thirdLineTitleStr = payStatusStr;
        thirdLineTitleColor = const Color(0xFFFF1800);
      } else {
        thirdLineTitleStr = "购买时间：";
        thirdLineDescStr = payTime;
      }
    }

    if (status == "finish" && belongDoctor.isNotEmpty) {
      // 所属医生 + 已使用
      thirdLineTitleStr = "购买时间：";
      thirdLineDescStr = payTime;
      fourLineTitleStr = "所属医生：";
      fourLineDescStr = belongDoctor;
    } else if (status == "untreated" && belongDoctor.isNotEmpty) {
      // 所属医生 + 未使用
      thirdLineTitleStr = "所属医生：";
      thirdLineDescStr = belongDoctor;
      if (payStatus == "toPay") {
        fourLineTitleStr = "未支付";
        fourLineTitleColor = const Color(0xFFFF1800);
      } else if (payStatus == "refunding") {
        thirdLineTitleStr = "购买时间：";
        thirdLineDescStr = payTime;
        fourLineTitleStr = "所属医生：";
        fourLineDescStr = belongDoctor;
        fiveLineTitleStr = "申请退款";
        fiveLineTitleColor = const Color(0xFFFF1800);
      } else if (payStatus == "paySuccess") {
        thirdLineTitleStr = "购买时间：";
        thirdLineDescStr = payTime;
        fourLineTitleStr = "所属医生：";
        fourLineDescStr = belongDoctor;
      }
    } else if (status == "refund" && belongDoctor.isNotEmpty) {
      // 所属医生 + 已退款
      thirdLineTitleStr = "购买时间：";
      thirdLineDescStr = payTime;
      fourLineTitleStr = "所属医生：";
      fourLineDescStr = belongDoctor;
    } else if (status == "finish" && orderSourceDoctor.isNotEmpty) {
      // 订单来源 + 已使用
      thirdLineTitleStr = "购买时间：";
      thirdLineDescStr = payTime;
      fourLineTitleStr = "订单来源：";
      fourLineDescStr = orderSourceDoctor;
    } else if (status == "untreated" && orderSourceDoctor.isNotEmpty) {
      // 订单来源 + 未使用
      thirdLineTitleStr = "订单来源：";
      thirdLineDescStr = orderSourceDoctor;
      if (payStatus == "toPay") {
        fourLineTitleStr = "未支付";
        fourLineTitleColor = const Color(0xFFFF1800);
      } else if (payStatus == "refunding") {
        thirdLineTitleStr = "购买时间：";
        thirdLineDescStr = payTime;
        fourLineTitleStr = "订单来源：";
        fourLineDescStr = orderSourceDoctor;
        fiveLineTitleStr = "申请退款";
        fiveLineTitleColor = const Color(0xFFFF1800);
      } else if (payStatus == "paySuccess") {
        thirdLineTitleStr = "购买时间：";
        thirdLineDescStr = payTime;
        fourLineTitleStr = "订单来源：";
        fourLineDescStr = orderSourceDoctor;
      }
    } else if (status == "refund" && orderSourceDoctor.isNotEmpty) {
      // 订单来源 + 已退款
      thirdLineTitleStr = "购买时间：";
      thirdLineDescStr = payTime;
      fourLineTitleStr = "订单来源：";
      fourLineDescStr = orderSourceDoctor;
    }

    return GestureDetector(
      behavior: HitTestBehavior.opaque, // 点击空白处也可以响应
      onTap: () => _jumpDetail(model),
      child: Container(
        width: double.infinity,
        color: Colors.white,
        child: Column(
          children: [
            SizedBox(
              height: 10.w,
              child: Container(color: Color(0xFFF5F5F5)),
            ),
            Container(
              padding: EdgeInsets.only(top: 12.w, bottom: 12.w, right: 12.w, left: 12.w),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  RichText(
                    text: TextSpan(children: [
                      TextSpan(
                        text: patientNameStr,
                        style: TextStyle(
                          color: ColorRes.color333333,
                          fontSize: 15.sp,
                          fontFamily: AppFonts.pingFangSC,
                          fontWeight: AppFonts.bold,
                        ),
                      ),
                      WidgetSpan(
                        child: SizedBox(
                          width: 20.w,
                        ),
                      ),
                      TextSpan(
                        text: ageAndSex,
                        style: TextStyle(
                          color: ColorRes.color666666,
                          fontSize: 15.sp,
                          fontFamily: AppFonts.pingFangSC,
                          fontWeight: AppFonts.medium,
                        ),
                      ),
                    ]),
                  ),
                  Text(
                    statusStr, // 新的文本内容
                    style: TextStyle(
                      color: statusColor,
                      fontSize: 14.sp,
                      fontFamily: AppFonts.pingFangSC,
                      fontWeight: AppFonts.medium,
                    ),
                  ),
                ],
              ),
            ),
            Container(
              padding: EdgeInsets.only(right: 12.w, left: 12.w),
              child: SizedBox(
                height: 1.w,
                child: Container(color: Color(0xFFF2F2F2)),
              ),
            ),
            Container(
              padding: EdgeInsets.only(top: 12.w, bottom: 3.w, right: 12.w, left: 12.w),
              width: double.infinity,
              color: ColorRes.white,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            Text(
                              "服务名称：",
                              style: TextStyle(
                                color: ColorRes.color666666,
                                fontSize: 14.sp,
                                fontFamily: AppFonts.pingFangSC,
                                fontWeight: AppFonts.medium,
                              ),
                            ),
                            Expanded(
                                child: Text(
                              "${model.drugName}",
                              maxLines: 1,
                              style: TextStyle(
                                color: ColorRes.color333333,
                                fontSize: 14.sp,
                                overflow: TextOverflow.ellipsis,
                                fontFamily: AppFonts.pingFangSC,
                                fontWeight: AppFonts.medium,
                              ),
                            )),
                          ],
                        ),
                        SizedBox(height: 5.w),
                        Row(children: [
                          Text(
                            "服务价格：",
                            style: TextStyle(
                              color: ColorRes.color666666,
                              fontSize: 14.sp,
                              fontFamily: AppFonts.pingFangSC,
                              fontWeight: AppFonts.medium,
                            ),
                          ),
                          Text(
                            "$servicePriceStr元",
                            maxLines: 1,
                            style: TextStyle(
                              color: ColorRes.color333333,
                              fontSize: 14.sp,
                              overflow: TextOverflow.ellipsis,
                              fontFamily: AppFonts.pingFangSC,
                              fontWeight: AppFonts.medium,
                            ),
                          )
                        ]),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Column(
                              children: [
                                SizedBox(height: 5.w),
                                Visibility(
                                    visible: thirdLineTitleStr.isNotEmpty,
                                    child: Row(
                                      children: [
                                        Text(
                                          thirdLineTitleStr,
                                          style: TextStyle(
                                            color: thirdLineTitleColor,
                                            fontSize: 14.sp,
                                            fontFamily: AppFonts.pingFangSC,
                                            fontWeight: AppFonts.medium,
                                          ),
                                        ),
                                        Visibility(
                                            visible: thirdLineDescStr.isNotEmpty,
                                            child: Text(
                                              thirdLineDescStr,
                                              style: TextStyle(
                                                color: thirdLineDescColor,
                                                fontSize: 14.sp,
                                                fontFamily: AppFonts.pingFangSC,
                                                fontWeight: AppFonts.medium,
                                              ),
                                            ))
                                      ],
                                    )),
                                SizedBox(height: 5.w),
                                Visibility(
                                    visible: fourLineTitleStr.isNotEmpty,
                                    child: Row(
                                      children: [
                                        Text(
                                          fourLineTitleStr,
                                          style: TextStyle(
                                            color: fourLineTitleColor,
                                            fontSize: 14.sp,
                                            fontFamily: AppFonts.pingFangSC,
                                            fontWeight: AppFonts.medium,
                                          ),
                                        ),
                                        Visibility(
                                            visible: fourLineDescStr.isNotEmpty,
                                            child: Text(
                                              fourLineDescStr,
                                              style: TextStyle(
                                                color: fourLineDescColor,
                                                fontSize: 14.sp,
                                                fontFamily: AppFonts.pingFangSC,
                                                fontWeight: AppFonts.medium,
                                              ),
                                            )),
                                      ],
                                    )),
                                SizedBox(height: 5.w),
                                Visibility(
                                    visible: fiveLineTitleStr.isNotEmpty,
                                    child: Text(
                                      fiveLineTitleStr,
                                      style: TextStyle(
                                        color: fiveLineTitleColor,
                                        fontSize: 14.sp,
                                        fontFamily: AppFonts.pingFangSC,
                                        fontWeight: AppFonts.medium,
                                      ),
                                    )),
                              ],
                            ),
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: [
                                Text(
                                  "查看详情",
                                  style: TextStyle(
                                    color: ColorRes.colorMain,
                                    fontSize: 14.sp,
                                    fontFamily: AppFonts.pingFangSC,
                                    fontWeight: AppFonts.medium,
                                  ),
                                ),
                                SizedBox(
                                  width: 1.w,
                                ),
                                ImageLoader.loadAsset("icon_right_more_arrow.webp", 14.w, color: ColorRes.colorMain),
                              ],
                            ),
                          ],
                        )
                      ],
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(
              height: 5.w,
              child: Container(color: Color(0xFFF5F5F5)),
            ),
          ],
        ),
      ),
    );
  }

  /// 调转到详情

  _jumpDetail(MyDoctorServiceListModel model) async {
    print("调转到详情 = ${model.toJson()}");
    context.push(PageUrl.doctorServiceDetails + "?id=${model.id}");
  }

  /// 获取申请退款列表 - 主要是为了红点🔴
  _getRefundApplicationList() async {
    var user = App.instance.userInfo;
    var httpRequest = HttpRequest(Api.refundApplicationList,
        body: {'doctorId': user?.id, "pageIndex": 1.toString(), "pageSize": 10.toString()});
    var httpResponse = await HttpClient.postJson(httpRequest);
    var serviceResult = ServiceResult<dynamic>.list(httpResponse, (map) => null);
    if (serviceResult.success) {
      var listCount = serviceResult.responseBody ?? [];
      print("serviceResult.responseBody ${serviceResult.responseBody}");
      print("申请退款列表：${listCount.length}");
      refundCount = listCount.length;
    }

    _getDoctorServiceList();
  }

  /// 获取项目成果列表
  _getDoctorServiceList() async {
    var user = App.instance.userInfo;
    print("项目成果列表tabbarKey：${tabbarKey}");
    var httpRequest = HttpRequest(Api.doctorServiceList, body: {
      'doctorId': user?.id,
      "status": tabbarKey,
      "pageIndex": pageNo.toString(),
      "pageSize": pageSize.toString()
    });
    var response = await HttpClient.postJson(httpRequest);

    var serviceResult = ServiceResult<List<MyDoctorServiceListModel>>.list(
        response, (map) => (map ?? []).map((e) => MyDoctorServiceListModel.fromJson(e)).toList());
    if (serviceResult.success) {
      var list = serviceResult.responseBody ?? [];
      print("项目成果列表：${list.toString()}");
      if (pageNo == 1) {
        dataArray.clear();
      }
      dataArray.addAll(list);

      if (list.length < pageSize) {
        _refreshController.loadNoData();
      } else {
        _refreshController.loadComplete();
      }
    }
    setState(() {
      dataLoaded = true;
    });
  }
}
